package com.jcl.core.security.filter;

import com.jcl.core.security.service.UserDetailService;
import com.jcl.core.security.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName JwtAuthenticationTokenFilter
 * @Description 确保在一次请求只通过一次filter，而不需要重复执行
 * @Author yyliu
 * @Date 2018/12/18 15:01
 * @Version 1.0
 **/
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private UserDetailService userDetailService;

    public JwtAuthenticationTokenFilter(UserDetailService userDetailService){
        this.userDetailService = userDetailService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        String authHeader = request.getHeader("Authorization");

        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String authToken = authHeader.substring("Bearer ".length());

            String username = JwtTokenUtil.getSubject(authToken);

            // 如果上面解析 token 成功并且拿到了 username 并且本次会话的权限还未被写入
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                // 用 UserDetailsService 从数据库中拿到用户的 UserDetails 类
                // UserDetails 类是 Spring Security 用于保存用户权限的实体类
                UserDetails userDetails = this.userDetailService.loadUserByUsername(username);
                if (userDetails != null) {
                    // 生成通过认证
                    UsernamePasswordAuthenticationToken authentication =
                            new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    // 将权限写入本次会话
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }

        chain.doFilter(request, response);
    }
}
